package com.android.takeaway.activity;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.android.takeaway.R;
import com.android.takeaway.adapter.CartAdapter;
import com.android.takeaway.adapter.MenuAdapter;
import com.android.takeaway.bean.Food;
import com.android.takeaway.bean.Shop;

/**
 * 店铺详情页面
 */
public class ShopDetailActivity extends AppCompatActivity implements View.OnClickListener {
    TextView tv_back, tv_title, tv_shapName, tv_shopNotice, tv_time, tv_count, tv_cost,
            tv_offerPrice, tv_checkOut, tv_clear;
    ImageView iv_shopPic, iv_cart;
    View include_cart_list;
    Shop shopBean; //当前店铺
    List<Food> foodBeanList, cartList; // 菜单列表数据 购物车列表数据
    RecyclerView recyclerView_menu, recyclerView_cart; //菜单列表 购物车列表
    MenuAdapter menuAdapter; //菜单适配器
    CartAdapter cartAdapter;//购物车适配器

    int totalCount;//购物车中食物数量
    BigDecimal totalMoney; //购物车中食物总价格

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_detail);
        initView();//初始化视图
        initData();//初始化数据
        initAdapter();//初始化适配器

    }

    private void initView() {
        //初始化返回按钮
        tv_back = findViewById(R.id.tv_back);
        tv_back.setOnClickListener(this); //监听器
        tv_title = findViewById(R.id.tv_title);
        tv_title.setText("店铺详情");
        tv_shapName = findViewById(R.id.tv_shopName);
        tv_shopNotice = findViewById(R.id.tv_shopNotice);
        tv_time = findViewById(R.id.tv_time);

        tv_count = findViewById(R.id.tv_count);
        tv_cost = findViewById(R.id.tv_cost);
        tv_offerPrice = findViewById(R.id.tv_offerPrice);
        tv_checkOut = findViewById(R.id.tv_checkOut);
        tv_checkOut.setOnClickListener(this);//添加事件
        iv_shopPic = findViewById(R.id.iv_shopPic);  //购物图片

        iv_cart = findViewById(R.id.iv_cart); //小红点 购物车图标
        iv_cart.setOnClickListener(this);

        recyclerView_menu = findViewById(R.id.recyclerView_menu);
        recyclerView_menu.setLayoutManager(new LinearLayoutManager(this));
        menuAdapter = new MenuAdapter(this); //初始化菜单数据适配器
        recyclerView_menu.setAdapter(menuAdapter);

        include_cart_list = findViewById(R.id.include_cart_list);
        //2周五的 初始化购物车列表
        recyclerView_cart = findViewById(R.id.recyclerView_cart);
        cartAdapter = new CartAdapter(this);
        recyclerView_cart.setLayoutManager(new LinearLayoutManager(this));
        recyclerView_cart.setAdapter(cartAdapter);
        tv_clear = findViewById(R.id.tv_clear);
        tv_clear.setOnClickListener(this);
    }
    private void initData() {
        totalCount = 0;
        totalMoney = new BigDecimal(0);
        //获得intent对象
        Intent intent = getIntent();
        //获取序列化对象
        shopBean = (Shop) intent.getSerializableExtra("shopBean");
        tv_shapName.setText(shopBean.getShopName());
        tv_shopNotice.setText(shopBean.getShopNotice());
        tv_time.setText(shopBean.getTime());
        foodBeanList = shopBean.getFoodList();
        // 获取图片的资源引用
        int resourceId = getResources().getIdentifier(shopBean.getShopPic(), "mipmap", getPackageName());
        Glide.with(this).load(resourceId).into(iv_shopPic);

        //初始化购物车列表
        cartList = new ArrayList<>();
        //cartList传给cartAdapter

    }

    private void initAdapter() {
        menuAdapter.setData(foodBeanList);  //给菜单适配器赋值
        tv_offerPrice.setText("起送价格：￥" + shopBean.getOfferPrice()); //显示起送价格
        menuAdapter.setOnAddButtonClickListener(new MenuAdapter.OnAddButtonClickListener() {
            @Override
            public void OnAddButtonClick(Food foodBean) {
                foodBean.setCount(foodBean.getCount() + 1); //购物车中数量+1
                if (!cartList.contains(foodBean)) {
                    cartList.add(foodBean);
                }
                cartAdapter.notifyDataSetChanged(); //操作修改之后界面刷新
                showCartMessage(); //显示购物车信息
            }
        });

        cartAdapter.setData(cartList); //给购物车数据适配器赋值
        cartAdapter.setOnItemChangedListener(new CartAdapter.OnItemChangedListener() {
            @Override
            public void onItemAdd(Food foodBean) {
                foodBean.setCount(foodBean.getCount() + 1);
                cartAdapter.notifyDataSetChanged();//刷新购物车列表
                showCartMessage();//刷新购物车界面
            }
            @Override
            public void onItemMinus(Food foodBean) {
                foodBean.setCount(foodBean.getCount() - 1);
                if (foodBean.getCount() < 1) {
                    cartList.remove(foodBean);
                }
                cartAdapter.notifyDataSetChanged();//刷新购物车列表
                showCartMessage();//刷新购物车界面
            }
        });
    }
    private void showCartMessage() {
        totalCount = 0;
        totalMoney = new BigDecimal(0);
        for (Object o : cartList) {
            Food foodBean = (Food) o;
            totalCount += foodBean.getCount(); //数量
            totalMoney = totalMoney.add(foodBean.getPrice().multiply(BigDecimal.valueOf(foodBean.getCount()))); //价格
        }
        if (totalCount > 0) { //已购物
            iv_cart.setImageResource(R.drawable.shop_car);
            tv_count.setText(totalCount + "");
            tv_count.setVisibility(View.VISIBLE);
            tv_cost.setText("￥" + totalMoney + "\n另需配送费 ￥" + shopBean.getDistributionCost());

            if (include_cart_list.getVisibility() == View.GONE) {
                include_cart_list.setVisibility(View.VISIBLE);
                //购物车出现的动画
                Animation animation = AnimationUtils.loadAnimation(this, R.anim.shopping_cart_animation);
                include_cart_list.startAnimation(animation);
            }

            if (totalMoney.compareTo(shopBean.getOfferPrice()) >= 0) {
                //显示去结账
                tv_checkOut.setVisibility(View.VISIBLE);
                tv_offerPrice.setVisibility(View.GONE);
            } else {
                //显示还差多少起送
                tv_checkOut.setVisibility(View.GONE);
                tv_offerPrice.setVisibility(View.VISIBLE);
                tv_offerPrice.setText("还差：￥" + shopBean.getOfferPrice().subtract(totalMoney));
            }
        } else { //未购物
            iv_cart.setImageResource(R.drawable.shop_car_empty);
            tv_count.setText("0");
            tv_count.setVisibility(View.GONE);
            tv_cost.setText(" 未选购商品 ");
            tv_checkOut.setVisibility(View.GONE);
            tv_offerPrice.setVisibility(View.VISIBLE);
            tv_offerPrice.setText("起送价格：￥" + shopBean.getOfferPrice()); //显示起送价格
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_checkOut:
                //打开订单activity
                Intent intent = new Intent(this, PayActivity.class);
                intent.putExtra("shopName", shopBean.getShopName());
                intent.putExtra("cartList", (Serializable) cartList);
                intent.putExtra("totalMoney", totalMoney);
                intent.putExtra("distributionCost", shopBean.getDistributionCost());
                startActivity(intent);
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.iv_cart:
                //显示或者隐藏购物车列表
                if (include_cart_list.getVisibility() == View.GONE) {
                    include_cart_list.setVisibility(View.VISIBLE);
                    //购物车出现的动画
                    Animation animation = AnimationUtils.loadAnimation(this, R.anim.shopping_cart_animation);
                    include_cart_list.startAnimation(animation);
                } else {
                    include_cart_list.setVisibility(View.GONE);
                    //购物车退出的动画
                    Animation animation = AnimationUtils.loadAnimation(this, R.anim.shopping_cart_animation_back);
                    include_cart_list.startAnimation(animation);
                }
                break;
            case R.id.tv_clear:
                //清空购物车
                clearCart();
                break;
        }
    }
    private void clearCart() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ShopDetailActivity.this);
        builder.setTitle("提示")
                .setIcon(R.drawable.remind)
                .setMessage("确定要清空购物车吗？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        for (Object o : cartList) {
                            Food foodBean = (Food) o;
                            foodBean.setCount(0);
                        }
                        cartList.clear();
                        //操作修改之后界面刷新
                        cartAdapter.notifyDataSetChanged();
                        include_cart_list.setVisibility(View.GONE);
                        //购物车出现的动画
                        Animation animation = AnimationUtils.loadAnimation(ShopDetailActivity.this, R.anim.shopping_cart_animation_back);
                        include_cart_list.startAnimation(animation);
                        //显示购物车信息
                        showCartMessage();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog dialog = builder.create();
        dialog.show();
    }


}